package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.UserDTO;
import com.cyzy.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserDTO> login(@RequestBody Map<String, Object> loginRequest) {
        try {
            Integer username = Integer.valueOf(loginRequest.get("username").toString());
            String password = loginRequest.get("password").toString();
            
            UserDTO user = userService.login(username, password);
            return Result.success("登录成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserDTO> register(@RequestBody Map<String, Object> registerRequest) {
        try {
            UserDTO userDTO = new UserDTO();
            userDTO.setUsername(Integer.valueOf(registerRequest.get("username").toString()));
            
            if (registerRequest.containsKey("nickname")) {
                userDTO.setNickname(registerRequest.get("nickname").toString());
            }
            if (registerRequest.containsKey("phone")) {
                userDTO.setPhone(registerRequest.get("phone").toString());
            }
            if (registerRequest.containsKey("role")) {
                userDTO.setRole(Integer.valueOf(registerRequest.get("role").toString()));
            } else {
                userDTO.setRole(0); // 默认为学生
            }
            
            String password = registerRequest.get("password").toString();
            
            UserDTO result = userService.register(userDTO, password);
            return Result.success("注册成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID查询用户信息（包含健康码）
     */
    @GetMapping("/{id}")
    public Result<UserDTO> getUserById(@PathVariable Integer id) {
        try {
            UserDTO user = userService.getUserById(id);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据用户名查询用户信息（包含健康码）
     */
    @GetMapping("/username/{username}")
    public Result<UserDTO> getUserByUsername(@PathVariable Integer username) {
        try {
            UserDTO user = userService.getUserByUsername(username);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户健康码信息
     */
    @GetMapping("/{id}/health-code")
    public Result<UserDTO> getUserHealthCode(@PathVariable Integer id) {
        try {
            UserDTO user = userService.getUserHealthCode(id);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有用户列表（分页）
     */
    @GetMapping("/list")
    public Result<Page<UserDTO>> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<UserDTO> users = userService.getAllUsers(pageable);
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据角色查询用户列表
     */
    @GetMapping("/role/{role}")
    public Result<List<UserDTO>> getUsersByRole(@PathVariable Integer role) {
        try {
            List<UserDTO> users = userService.getUsersByRole(role);
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有教师列表
     */
    @GetMapping("/teachers")
    public Result<List<UserDTO>> getAllTeachers() {
        try {
            List<UserDTO> teachers = userService.getAllTeachers();
            return Result.success(teachers);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有学生列表
     */
    @GetMapping("/students")
    public Result<List<UserDTO>> getAllStudents() {
        try {
            List<UserDTO> students = userService.getAllStudents();
            return Result.success(students);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID查询学生列表
     */
    @GetMapping("/class/{classId}/students")
    public Result<List<UserDTO>> getStudentsByClassId(@PathVariable Integer classId) {
        try {
            List<UserDTO> students = userService.getStudentsByClassId(classId);
            return Result.success(students);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID查询班级中的所有用户
     */
    @GetMapping("/class/{classId}")
    public Result<List<UserDTO>> getUsersByClassId(@PathVariable Integer classId) {
        try {
            List<UserDTO> users = userService.getUsersByClassId(classId);
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户基本信息
     */
    @PutMapping("/{id}")
    public Result<UserDTO> updateUserProfile(@PathVariable Integer id, 
                                           @Valid @RequestBody UserDTO userDTO) {
        try {
            UserDTO result = userService.updateUserProfile(id, userDTO);
            return Result.success("用户信息更新成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 检查用户是否存在
     */
    @GetMapping("/exists/{username}")
    public Result<Boolean> userExists(@PathVariable Integer username) {
        try {
            boolean exists = userService.userExists(username);
            return Result.success(exists);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户切换（获取可切换的用户列表）
     */
    @GetMapping("/switchable")
    public Result<List<UserDTO>> getSwitchableUsers() {
        try {
            // 获取所有用户列表，前端可以选择切换
            List<UserDTO> allStudents = userService.getAllStudents();
            List<UserDTO> allTeachers = userService.getAllTeachers();
            
            allStudents.addAll(allTeachers);
            return Result.success("获取可切换用户列表成功", allStudents);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 模拟切换用户（返回指定用户的完整信息）
     */
    @PostMapping("/switch")
    public Result<UserDTO> switchUser(@RequestBody Map<String, Object> switchRequest) {
        try {
            Integer targetUserId = Integer.valueOf(switchRequest.get("targetUserId").toString());
            UserDTO user = userService.getUserById(targetUserId);
            return Result.success("切换用户成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}





